package cocurrent;

import org.junit.Test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量   用于限流
 */
public class SemaphoreTest {
    @Test
    public void test() throws InterruptedException {
        Semaphore s = new Semaphore(1, false);//只能同时有1个线程能做事 不公平
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                try {
                    s.acquire();
                    TimeUnit.SECONDS.sleep(1);
                    s.release();
                    System.out.println("done~~");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
        for (int i = 0; i < 10; i++) {
            threads[i].join();
        }
    }

}
